import type { ConfModel } from '@/apis/model/conf'
import type { AdminModel } from '@/apis/types/admin'
import { defineStore } from 'pinia'
import { getApplicationsApi } from '@/apis/modules/application'
import { addCdnCountryApi } from '@/apis/modules/cdn'
import { getConfApi } from '@/apis/modules/conf'
import { SOTRE_KEY } from '@/constants/key'
import { CookieHelper } from '@/utils/cookie.helper'

export const useAppStore = defineStore(
  SOTRE_KEY,
  () => {
    const adminInfo = ref<AdminModel>()
    const router = useRouter()
    const CountryCode = ref([])
    const appList = ref([])

    const clearLoginInfoAction = () => {
      adminInfo.value = undefined
      CookieHelper.remove()
      router.replace('/sign-in')
    }

    const googleVerify = ref(false)
    async function getBaseInfo() {
      return getConfApi({ type: 1 }).then((res: ConfModel) => {
        googleVerify.value = Number(res.base_conf?.google_verify ?? 1) === 1
      })
    }

    async function getCountryCode() {
      return addCdnCountryApi({}).then((res: ConfModel) => {
        CountryCode.value = res?.list || []
      })
    }

    async function getApplications() {
      return getApplicationsApi({ limit: 500 }).then((res: ConfModel) => {
        appList.value = (res.list || []).map((item) => {
          return {
            label: item.name!,
            value: item.app_id!,
          }
        })
      })
    }

    return {
      adminInfo,
      googleVerify,
      CountryCode,
      appList,
      getCountryCode,
      getBaseInfo,
      clearLoginInfoAction,
      getApplications,
    }
  },
  {
    persist: {
      pick: ['adminInfo'],
    },
  },
)
